import {createRouter, createWebHistory} from 'vue-router'
import store from '../store'
import HomeView from "@/views/HomeView.vue"; // 新增store引入

const routes = [
    {
        path: '/home',
        name: 'home',
        component: HomeView,
        meta: {requiresAuth: true},
        children: [
            {
                path: '/dashboard',
                name: 'dashboard',
                component: () => import('../views/DashboardView.vue'),
                meta: {title: '首页', icon: 'el-icon-s-data'}
            },
            {
                path: '/profile',
                name: 'profile',
                component: () => import('../views/ProfileView.vue'),
                meta: {title: '个人信息', icon: 'el-icon-user', requiresNormalUser: true, hiddenForAdmin: true}
            },
            {
                path: '/academic-origin',
                name: 'academic-origin',
                component: () => import('../views/AcademicOriginView.vue'),
                meta: {title: '学缘信息', icon: 'el-icon-s-order', requiresNormalUser: true, hiddenForAdmin: true}
            },
            {
                path: '/research',
                name: 'research',
                component: () => import('../views/ResearchView.vue'),
                meta: {
                    title: '科研成果', icon: 'el-icon-document', requiresNormalUser: true, hiddenForAdmin: true
                }
            },
            {
                path: '/user-management',
                name: 'user-management',
                component: () => import('../views/UserManagementView.vue'),
                meta: {title: '人员管理', icon: 'el-icon-s-custom', requiresAdmin: true}
            },
            {
                path: '/research-management',
                name: 'research-management',
                component: () => import('../views/ResearchManagementView.vue'),
                meta: {title: '科研管理', icon: 'el-icon-s-custom', requiresAdmin: true}
            }
        ]
    },
    {
        path: '/',
        name: 'login',
        component: () => import('../views/HalfLoginView.vue')
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

// 添加全局路由守卫检查token
router.beforeEach((to, from, next) => {
    const hasToken = store.getters.token;
    const isLoginRoute = to.path === '/';
    const isProtectedRoute = to.path === '/home';
    const isAdminRoute = to.meta.requiresAdmin;
    const isNormalUserRoute = to.meta.requiresNormalUser;
    const isAdmin = store.state.role === 'admin';
    const isNormalUser = store.state.role === 'normal';
    if (isProtectedRoute) {
        hasToken ? next() : next('/');
    } else if (isLoginRoute) {
        hasToken ? next('/home') : next();
    } else if (isAdminRoute && !isAdmin) {
        next('/home');
    } else if (isNormalUserRoute && !isNormalUser) {
        next('/home');
    } else {
        next();
    }
});

export default router